package com.lzh.db.config;

import com.baomidou.mybatisplus.core.handlers.StrictFill;
import com.lzh.db.handler.LzhMetaObjectHandler;
import com.lzh.db.properties.MybatisPlusAutoFillProperties;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zhehen.lu
 * @date 2025/8/15 11:00
 */
public class DateMetaObjectHandler implements LzhMetaObjectHandler {
    @Autowired
    private MybatisPlusAutoFillProperties mybatisPlusAutoFillProperties;

    public DateMetaObjectHandler() {
    }

    @Override
    public void insertFill(MetaObject object) {
        boolean createTimeIsExist = object.hasGetter(this.mybatisPlusAutoFillProperties.getCreateTimeField());
        boolean updateTimeIsExist = object.hasGetter(this.mybatisPlusAutoFillProperties.getUpdateTimeField());
        Date date = this.getDate();
        List<StrictFill<?, ?>> list = new ArrayList();
        if (createTimeIsExist) {
            list.add(StrictFill.of(this.mybatisPlusAutoFillProperties.getCreateTimeField(), Date.class, date));
        }

        if (updateTimeIsExist) {
            list.add(StrictFill.of(this.mybatisPlusAutoFillProperties.getUpdateTimeField(), Date.class, date));
        }

        if (!CollectionUtils.isEmpty(list)) {
            this.strictInsertFill(this.findTableInfo(object), object, list);
        }

    }

    @Override
    public void updateFill(MetaObject object) {
        boolean updateTimeIsExist = object.hasGetter(this.mybatisPlusAutoFillProperties.getUpdateTimeField());
        Date date = this.getDate();
        List<StrictFill<?, ?>> list = new ArrayList();
        if (updateTimeIsExist) {
            list.add(StrictFill.of(this.mybatisPlusAutoFillProperties.getUpdateTimeField(), Date.class, date));
        }

        if (!CollectionUtils.isEmpty(list)) {
            this.strictUpdateFill(this.findTableInfo(object), object, list);
        }

    }

    private Date getDate() {
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.set(14, 0);
        return instance.getTime();
    }
}